<template>
  <div class="filter-life-cycle consumption-container">
    <div class="flex-center table-top">
      <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
        <px-form-item label="设备编号" prop="ffuCode">
          <px-input v-model.trim="queryParams.ffuCode" placeholder="请输入设备编号" clearable />
        </px-form-item>

        <px-form-item label="Filter类型" prop="type">
          <px-select v-model="queryParams.type" placeholder="请选择Filter类型" clearable filterable>
            <px-option v-for="item in filterTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>

        <px-form-item label="滤芯型号" prop="filterSpec">
          <px-select v-model="queryParams.filterSpec" placeholder="请选择滤芯型号" clearable filterable>
            <px-option v-for="item in filterSpcOptions" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>

        <px-form-item label="滤壳型号" prop="filterCode">
          <px-select v-model="queryParams.filterCode" placeholder="请选择滤壳型号" clearable filterable>
            <px-option v-for="item in filterCodeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>

        <px-form-item label="点位" prop="position">
          <px-select v-model="queryParams.position" placeholder="请选择点位" clearable filterable>
            <px-option v-for="item in positionOptions" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>

        <px-form-item label="状态" prop="status">
          <px-select v-model="queryParams.status" placeholder="请选择状态" clearable filterable>
            <px-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>

        <div class="search-form-btn flexNowrap">
          <px-button type="primary" @click="handleQuery">查询</px-button>
          <px-button @click="resetQuery">重置</px-button>
        </div>
      </px-form>
    </div>

    <div ref="objectModelTableRef" class="table-content">
      <px-table
        v-loading="loading"
        :data="tableData"
        size="small"
        border
        class="common-table"
        :header-cell-style="headerCellStyleFn"
        :cell-style="cellStyleFn"
        :span-method="objectSpanMethod"
        :height="scrollbarHeight"
      >
        <!-- <px-table-column type="index" label="序号"  width="55" align="center" /> -->
        <px-table-column prop="ffuCode" label="设备编号" min-width="100" show-overflow-tooltip />
        <px-table-column prop="filterType" label="Filter类型" min-width="60" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ filterTypeMap.get(scope.row.filterType) || "--" }}</span>
          </template>
        </px-table-column>
        <px-table-column prop="position" label="点位" min-width="50" show-overflow-tooltip />
        <px-table-column prop="filterCode" label="滤壳型号" min-width="80" show-overflow-tooltip />
        <px-table-column prop="filterSpc" label="滤芯型号" min-width="80" show-overflow-tooltip />
        <px-table-column prop="filterNumber" label="数量" min-width="50" show-overflow-tooltip />
        <px-table-column prop="filterInstallDate" label="开始使用日期" min-width="80" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.filterInstallDate || "--" }}</span>
          </template>
        </px-table-column>
        <px-table-column prop="lifecycle_exp" label="额定寿命(天)" min-width="60" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.filterInstallDate ? (row.lifecycle_exp ?? "--") : "--" }}</span>
          </template>
        </px-table-column>
        <px-table-column prop="lifecycle_predict" label="预测寿命(天)" min-width="60" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.filterInstallDate ? (row.lifecycle_predict ?? "--") : "--" }}</span>
          </template>
        </px-table-column>
        <px-table-column label="使用情况" min-width="170">
          <template #default="{ row }">
            <div v-if="row.filterInstallDate" class="flexRow">
              <px-progress
                :percentage="((row.lifecycle_exp - row.lifecycle_exp_left) / row.lifecycle_exp) * 100"
                :stroke-width="16"
                :text-inside="true"
              >
                <span>已使用{{ row.lifecycle_exp - row.lifecycle_exp_left }}天</span>
              </px-progress>
              <px-text v-if="row.invalid" type="danger">剩余{{ row.lifecycle_exp_left }}天</px-text>
              <px-text v-else-if="row.outdated" type="warning">剩余{{ row.lifecycle_exp_left }}天</px-text>
              <px-text v-else type="success">剩余{{ row.lifecycle_exp_left }}天</px-text>
            </div>
            <div v-else>{{ "--" }}</div>
          </template>
        </px-table-column>
        <px-table-column label="状态" min-width="70">
          <template #default="{ row }">
            <px-button v-if="row.invalid" plain type="danger" size="small">失效</px-button>
            <px-button v-else-if="row.outdated" plain type="warning" size="small">临期</px-button>
            <px-button v-else plain type="success" size="small">健康</px-button>
          </template>
        </px-table-column>
        <px-table-column prop="pressure" label="压差（MPa）" min-width="80" show-overflow-tooltip />
        <px-table-column prop="filterExtra" label="Spec" min-width="90">
          <template #default="{ row, $index }">
            <div v-if="editRowIndex === $index" v-has="'GAS_OPERATION_FILTER_LIFE_CYCLE_MANAGE_EDIT_BTN'" class="flexRow">
              <px-input v-model.trim="row.filterExtra" />
              <px-button link icon="Save" @click="handleSave(row)" />
            </div>
            <div v-else>
              <span>{{ row.filterExtra }}</span>
              <px-button
                v-if="!(editRowIndex < tableData.length && editRowIndex > -1)"
                v-has="'GAS_OPERATION_FILTER_LIFE_CYCLE_MANAGE_EDIT_BTN'"
                link
                icon="Edit"
                @click="handleEdit($index)"
              />
            </div>
          </template>
        </px-table-column>

        <px-table-column prop="filterNextInstallDate" label="下次更换日期" min-width="100">
          <template #default="{ row }">
            <px-button link icon="NotificationFilled" type="danger" />
            <span>{{ row.filterNextInstallDate }}</span>
          </template>
        </px-table-column>
        <px-table-column label="操作" width="170" align="center" fixed="right">
          <template #default="scope">
            <px-tooltip content="查看曲线" placement="top">
              <px-button
                v-has="'GAS_OPERATION_FILTER_LIFE_CYCLE_MANAGE_CURVE_BTN'"
                :disabled="!scope.row?.positionNum?.length"
                link
                icon="BusinessMeasurement"
                type="primary"
                @click="viewChartLine(scope.row)"
              />
            </px-tooltip>
            <px-tooltip content="更换" placement="top">
              <px-button
                v-has="'GAS_OPERATION_FILTER_LIFE_CYCLE_MANAGE_CHANGE_BTN'"
                link
                icon="Switch"
                type="primary"
                @click="handleSwitch(scope.row)"
              />
            </px-tooltip>
            <px-tooltip content="耗材记录" placement="top">
              <px-button
                v-has="'GAS_OPERATION_FILTER_LIFE_CYCLE_MANAGE_RECORD_BTN'"
                link
                icon="Document"
                type="primary"
                @click="handleRecord(scope.row)"
              />
            </px-tooltip>
            <px-tooltip content="工单记录" placement="top">
              <px-button
                v-has="'GAS_OPERATION_FILTER_LIFE_CYCLE_MANAGE_ORDER_BTN'"
                link
                icon="Tickets"
                type="primary"
                @click="handleTicktes(scope.row)"
              />
            </px-tooltip>
          </template>
        </px-table-column>
        <template #empty>
          <px-empty class="px-empty-common" />
        </template>
      </px-table>
    </div>
    <analysisChart v-if="visible" v-model:visible="visible" :pointNum="pointNum" />
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "GAS_OPERATION_FILTER_LIFE_CYCLE_MANAGE"
});
import { ref, reactive, markRaw, onMounted, onUnmounted } from "vue";
import { BusinessMeasurement, Switch, Document, Tickets, NotificationFilled, Edit } from "@px-ui/icons-vue";
import { PxMessage } from "px-ui";
import { useRouter } from "vue-router";
import { getToken } from "@/utils/auth";
import analysisChart from "./components/analysis.vue";
import {
  queryFilterList,
  queryFilterPointNum,
  queryLastScadaValue,
  updateExtra,
  queryNameByTypeCodeAndValue,
  queryList,
  queryListByEqpIdAndIdentify,
  queryByEqpIdAndIdentify
} from "@/api/modules/operation";
// import { queryDictData } from "@/api/common";
// import { queryChildByTypeCodeAndItemValue } from "@/api/handover.ts";
import { filterTypeMap, filterSpcMap, filterCodeMap, positionMap } from "@/views/gas/utils";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";

const router = useRouter();

const gap = 40;
const defaultHeight = 606;
const scrollbarHeight = ref<number>(defaultHeight);
const objectModelTableRef = ref<HTMLElement | null>(null);

// Filter类型
const filterTypeOptions = Array.from(filterTypeMap)?.map(m => ({ value: m[0], label: m[1] }));
// 滤芯型号
const filterSpcOptions = Array.from(filterSpcMap)?.map(m => ({ value: m[0], label: m[1] }));
// 滤壳型号
const filterCodeOptions = Array.from(filterCodeMap)?.map(m => ({ value: m[0], label: m[1] }));
// 点位
const positionOptions = Array.from(positionMap)?.map(m => ({ value: m[0], label: m[1] }));

//状态下拉
const statusOptions = [
  {
    label: "失效",
    value: 1
  },
  {
    label: "临期",
    value: 2
  },
  {
    label: "健康",
    value: 3
  }
];
const visible = ref(false);
const pointNum = ref("");
const viewChartLine = row => {
  pointNum.value = row.positionNum;
  visible.value = true;
};
const queryParams = reactive({
  ffuCode: "",
  type: "",
  filterSpec: "",
  filterCode: "",
  position: "",
  status: ""
});
const tableData = ref([]);

const objectSpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  if (columnIndex === 0) {
    return {
      rowspan: row.rowspan || 0,
      colspan: row.rowspan ? 1 : 0
    };
  } else if (columnIndex === 1) {
    return {
      rowspan: row.rowspan2 || 0,
      colspan: row.rowspan2 ? 1 : 0
    };
  }
};

//根据指标id查询压差
// const searchLastScadaValue = async (positionNumList, eqpId) => {
//   // const params = { strings: positionNumList };
//   const res = await queryLastScadaValue(positionNumList);
//   tableData.value.forEach(v => {
//     if (v.ffuCode === eqpId) {
//       const { length } = res.rows;
//       if (length > 0) {
//         v.pressure = res.rows[length - 1].last_value;
//       } else {
//         v.pressure = "";
//       }
//     }
//   });
// };
// const searchPointNumssss = async eqpId => {
//   const params = { eqpId, attributeType: "DYNAMIC", hidden: 1 };
//   const res = await queryList(params);
//   const positionNumList = res.map(v => {
//     return v.positionNum;
//   });
//   searchLastScadaValue(positionNumList, eqpId);

//   //遍历表格数据，对设备编码一样的数据插入压差
//   tableData.value.forEach(v => {
//     if (v.ffuCode === eqpId) {
//       v.positionNum = positionNumList;
//     }
//   });
// };
const loading = ref(false);
const handleQuery = async () => {
  loading.value = true;
  tableData.value = [];
  //后台没有状态数据，传参去掉
  const devId = [];
  if (queryParams.ffuCode) {
    devId.push(queryParams.ffuCode);
  }
  const { ffuCode, status, ...ep } = queryParams;
  // const params = { devId, filterSpc: queryParams.filterSpc, devType: "Unit" };
  const params = { ...ep, devId, devType: "Unit" };
  const res = await queryFilterList(params);
  if (res.success === true) {
    let filterList = res.ffuList
      .map(v => {
        return v.filters;
      })
      .flat();
    //过滤出符合筛选状态的数据
    if (queryParams.status) {
      if (queryParams.status === 1) {
        //1失效
        filterList = filterList.filter(v => {
          return v.invalid;
        });
      } else if (queryParams.status === 2) {
        //2临期
        filterList = filterList.filter(v => {
          return v.outdated && !v.invalid;
        });
      } else {
        //3健康
        filterList = filterList.filter(v => {
          return !v.invalid && !v.outdated;
        });
      }
    }
    // const eqpIdList = filterList.map(v => {
    //   return v.ffuCode;
    // });
    // searchPointNum(eqpIdList);
    // filterList.forEach(v => {
    //   // searchPointNumssss(v.ffuCode);
    // });
    const eqpIds = filterList.map(item => item.ffuCode);
    // const params = { attributeIdentifyList: ["pressure"], eqpIdList };
    const params = { identifies: ["pressure"], eqpIds };
    // const res2 = await queryListByEqpIdAndIdentify(params);
    let res2 = await queryByEqpIdAndIdentify(params);
    // const positionNumList = res2.map(item => item.positionNum);
    res2 = Object.values(res2).map(item => item.pressure);
    const positionNumList = res2?.map(item => item.measureCode);
    if (!positionNumList.length) return;
    const res3 = await queryLastScadaValue(positionNumList);
    const res4 = res2?.reduce((pre, cur) => {
      // const t = res3.rows?.find(ite => ite.point === cur.positionNum);
      const t = res3.rows?.find(ite => ite.point === cur.measureCode);
      if (t) {
        pre.push({ ...cur, ...t });
      } else {
        pre.push({ ...cur });
      }
      return pre;
    }, []);
    filterList = filterList?.map(item => {
      const t = res4?.find(ite => ite.eqpId === item.ffuCode);
      if (t) {
        const pressure = t?.last_value || "--";
        // const positionNum = [t.positionNum];
        const positionNum = [t.measureCode];
        item = { ...item, pressure, positionNum };
      } else {
        item = { ...item, pressure: "--", positionNum: [] };
      }
      return item;
    });
    tableData.value = formatSpanFn(filterList);
  }
  loading.value = false;
};

const formatSpanFn = (data: Array<any>): Array<any> => {
  if (!data?.length) return [];
  let currentFfuCode = data[0].ffuCode;
  let currentFfuCodeNum = 0;
  let currentFilterType = data[0].filterType;
  let currentFilterTypeNum = 0;
  data?.forEach((item, index, arr) => {
    const { ffuCode, filterType } = item;
    currentFfuCodeNum++;
    currentFilterTypeNum++;
    if (ffuCode !== arr[index + 1]?.ffuCode) {
      data[index - currentFfuCodeNum + 1]["rowspan"] = currentFfuCodeNum;
      currentFfuCode = arr[index + 1]?.ffuCode;
      currentFfuCodeNum = 0;
      data[index - currentFilterTypeNum + 1]["rowspan2"] = currentFilterTypeNum;
      currentFilterType = arr[index + 1]?.filterType;
      currentFilterTypeNum = 0;
    } else {
      if (filterType !== arr[index + 1]?.filterType) {
        data[index - currentFilterTypeNum + 1]["rowspan2"] = currentFilterTypeNum;
        currentFilterType = arr[index + 1]?.filterType;
        currentFilterTypeNum = 0;
      }
    }
  });
  return data;
};

const formRef = ref(null);
const resetQuery = () => {
  formRef.value.resetFields();
  handleQuery();
};
//字典查询接口
const dicDataString = ref("");
const searchDictionaryData = async () => {
  const res = await queryNameByTypeCodeAndValue({
    typeCode: "CONSUMABLE_LIFE_CYCLE",
    itemValue: "EQP_RO"
  });
  dicDataString.value = res.itemDesc;
};

onMounted(async () => {
  handleQuery();
  searchDictionaryData();
  await useUpdateDomHeight(scrollbarHeight, objectModelTableRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());

const accessToken = getToken().accessToken || "";
//跳转到耗材记录
const handleRecord = row => {
  router.push({
    path: "/gas/operation/filterLifeCycle/record",
    query: {
      ffuCode: row.ffuCode,
      filterSpc: row.filterSpc
      // className: "GAS" //GAS:气课，MACHINE:机械科,ELECTRICTITY:电科，WATER：水科
    }
  });
};

const facCode = localStorage.getItem("facCode");

const handleSwitch = row => {
  const { position, filterType } = row;
  const source = `${filterType}-${position}`;
  const { EQP_TYPE_ID, SPARE_PART_SPECIFICATION_CODE } = JSON.parse(dicDataString.value);
  //跳转至突发型保养计划
  router.push({
    path: "/all/equip/epm/plan/list",
    query: {
      fullpath: `/pmPlan/list?pmType=UNS&isAdd=true&ssoToken=${accessToken}&isHiddenMenu=true&eqpId=${EQP_TYPE_ID}&ruleCode=${SPARE_PART_SPECIFICATION_CODE}&facCode=${facCode}&className=GAS&subType=REF_TEMPLATE&source=${source}`
    }
  });
};

const handleTicktes = () => {
  const { EQP_TYPE_ID, SPARE_PART_SPECIFICATION_CODE } = JSON.parse(dicDataString.value);
  //跳转至pms任务列表页
  router.push({
    path: "/all/equip/epm/task/list",
    query: {
      fullpath: `/pmJob/list?ssoToken=${accessToken}&isHiddenMenu=true&eqpId=${EQP_TYPE_ID}&ruleCode=${SPARE_PART_SPECIFICATION_CODE}&className=GAS&jobStatus=["COMPLETED","ONGOING","CREATED"]&facCode=${facCode}`
    }
  });
};
const editRowIndex = ref(-1);
const handleEdit = idx => {
  editRowIndex.value = idx;
};
const handleSave = async row => {
  const { ffuCode, filterExtra: extra, position, filterType, filterSpc } = row;
  editRowIndex.value = -1;
  const devId = [ffuCode];
  const params = { devId, extra, position, filterType, filterSpc };
  const res = await updateExtra(params);
  if (res.success === true) {
    PxMessage.success("保存成功");
    handleQuery();
  }
};
const headerCellStyleFn = () => {
  const style = {};
  style["background-color"] = "var(--px-color-primary-light-9) !important";
  return style;
};

const cellStyleFn = () => {
  return { fontSize: "14px" };
};
</script>
<style lang="scss" scoped>
@import url("@/views/gas/consumption/scss/common.scss");

.filter-life-cycle {
  width: 100%;
  background-color: #fff;

  &-search {
    width: 100%;
  }

  :deep(.px-form-item) {
    width: 100%;

    .px-input__wrapper {
      border: none;

      &.is-focus {
        border: none;
        box-shadow: none;
      }
    }
  }

  .setContent-content-table {
    margin-top: 16px;
  }

  .flexRow {
    display: flex;
    flex-direction: row;
    gap: 2px;
    width: 100%;
  }

  :deep(.px-progress) {
    flex: 1;
  }

  .flexNowrap {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
  }
}
</style>
